package com.walle.sonar.export.report.api.rules;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.jayway.jsonpath.ReadContext;
import com.jayway.jsonpath.TypeRef;
import com.walle.ak47.commons.utils.FileUtils;
import com.walle.ak47.commons.utils.HttpClientPool;
import com.walle.ak47.commons.utils._JsonPath;
import com.walle.ak47.commons.utils.json.GBuilder;
import com.walle.sonar.export.report.reportdoc.Config;

public class GetRules {
	
	static String get_all_rule_url = "http://127.0.0.1:9000/api/rules/search?f=isTemplate,name,lang,langName,severity,status,sysTags,tags,templateKey,actives,params&facets=languages,types&ps=100&s=name&activation=true&qprofile=AWicRrkPoioUpxa-fJ8f"+Config._type ;
	public static List<String> getAllRuleKeys() {
		
		HashMap<String, Object> _headers = new HashMap<String, Object>();
		String result = HttpClientPool.httpGet(get_all_rule_url, _headers);
		
		ReadContext parse = _JsonPath.parse(result);
		List<String> ruleKeys = _JsonPath.read(parse, "$.rules[*].key", new TypeRef<List<String>>() {}  );
		
		String ruleKeysMap = GBuilder.toJson(ruleKeys);
		FileUtils.writeFileText("E:/1.txt", ruleKeysMap) ;
		
		return ruleKeys ;
	}
	
	static String get_ruleInfo_by_key_url  = "http://127.0.0.1:9000/api/rules/show?actives=true&key=" ;
	public static RuleInfo getRuleInfoByKey(String ruleKey) {
		
		HashMap<String, Object> _headers = new HashMap<String, Object>();
		String result = HttpClientPool.httpGet(get_ruleInfo_by_key_url+ruleKey , _headers);
		ReadContext parse = _JsonPath.parse(result);
		Map<String,Object> rule  = _JsonPath.read(parse, "$.rule", new TypeRef<Map<String,Object>>() {}  );
		return new RuleInfo(rule.get("key").toString(), rule.get("name").toString(), rule.get("mdDesc").toString(), rule.get("mdNote")==null?null:rule.get("mdNote").toString() ) ;
	}
	
	public static List<RuleInfo> getRuleInfos() {
		
		List<RuleInfo> ruleInfos = new ArrayList<RuleInfo>();
		getAllRuleKeys().forEach(action->{
			
			ruleInfos.add( getRuleInfoByKey(action)) ;
		});
		
		return ruleInfos ;
	}
	
	public static Map<String,RuleInfo> getRuleInfosForMap() {
		
		Map<String,RuleInfo> ruleInfos = new HashMap<String,RuleInfo>();
		getAllRuleKeys().forEach(action->{
			
			RuleInfo ruleInfo = getRuleInfoByKey(action);
			ruleInfos.put( ruleInfo.getKey(), ruleInfo ) ;
		});
		
		return ruleInfos ;
	}
	
	
	public static void main(String[] args) {
		System.err.println( GBuilder.toJson( GetRules.getRuleInfos() ) );
	}
}
